package com.thingcom.delinrobot.main.device;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.android.tu.loadingdialog.LoadingDailog;
import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.gizwits.gizwifisdk.enumration.GizWifiDeviceNetStatus;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.thingcom.delinrobot.Common.Frame.FrameUtils;
import com.thingcom.delinrobot.Common.Frame.SetPinNum;
import com.thingcom.delinrobot.Common.pjo.FrameType;
import com.thingcom.delinrobot.Data.GizManger;
import com.thingcom.delinrobot.R;
import com.thingcom.delinrobot.base.BaseBackFragment;
import com.thingcom.delinrobot.main.adddevice.DeviceListActivity;
import com.thingcom.delinrobot.utils.AppUtils;
import com.thingcom.delinrobot.utils.HexStrUtils;
import com.thingcom.delinrobot.utils.MyLog;
import com.thingcom.delinrobot.utils.PreferencesUtil;
import com.thingcom.delinrobot.utils.ToastUtil;
import com.thingcom.delinrobot.view.SimpleToolbar;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.thingcom.delinrobot.utils.AppUtils.hideSoftKeyboard;

/**
 * author : YuFeng
 * e-mail : 923462992@qq.com
 * date   : 2019/11/20
 */
public class DevicePinFragment extends BaseBackFragment implements GizManger.myGizWifiDeviceListener{

    @BindView(R.id.toolbar_device_pin)
    SimpleToolbar toolbarDevicePin;
    @BindView(R.id.btn_pin_enter)
    Button btnPinEnter;
    @BindView(R.id.cb_pin)
    CheckBox cbPin;
    @BindView(R.id.et_device_password)
    TextInputEditText etDevicePassword;
    @BindView(R.id.til_device_password)
    TextInputLayout tilDevicePassword;
    @BindView(R.id.cl_device_pin)
    ConstraintLayout clDevicePin;
    private Boolean checkBox = false;
    private LoadingDailog dialog;
    // 再点一次退出程序时间设置
    private static final long WAIT_TIME = 2000L;
    private long TOUCH_TIME = 0;

    public static DevicePinFragment newInstance() {
        Bundle args = new Bundle();
        DevicePinFragment fragment = new DevicePinFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_back_device_pin, container, false);
        unbinder = ButterKnife.bind(this, view);
        ColorStateList colorStateList = getResources().getColorStateList(R.color.text_input_edit_selectoe);
        tilDevicePassword.setBoxStrokeColorStateList(colorStateList);
        clDevicePin.setOnTouchListener((v, event) -> {
            clDevicePin.clearFocus();
            hideSoftKeyboard(getContext(), clDevicePin);
            return false;
        });
        GizManger.getInstance().setmCallback(this);
        initToolbar(toolbarDevicePin);
        toolbarDevicePin.setLeftIconClickListener(view1 -> {
            GizManger.getInstance().unSubcriber();
           // pop();
        });
        etDevicePassword.setInputType(EditorInfo.TYPE_CLASS_PHONE);
        String psw = PreferencesUtil.getInstance(getContext()).getString("PIN",null);
        checkBox = PreferencesUtil.getInstance(getContext()).getBoolean("CBPIN",false);
        cbPin.setChecked(checkBox);
        if (psw!=null){
            etDevicePassword.setText(psw);
        } else {
            PreferencesUtil.getInstance(getContext()).putBoolean("CBPIN",false);
        }
        return view;
    }

    @OnClick({R.id.btn_pin_enter, R.id.cb_pin})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_pin_enter:
                if (AppUtils.isFastDoubleClick(3000)) {
                    return;
                }
                String psw = Objects.requireNonNull(etDevicePassword.getText()).toString();
               if (psw.length()!=4){
                   ToastUtil.showToast(getContext(),"密码格式不正确");
                   return;
               }
                Log.i("pin输入", "onViewClicked: "+psw);
                byte[] dataPsw = new byte[4];
                for (int i =0;i<4;i++){
                    String perPsw = psw.substring(i,i+1);
                    dataPsw[i] = Byte.parseByte("0"+perPsw);
                }
                try {
                    Thread.sleep(400);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                SetPinNum setPinNum =new SetPinNum("00000000",dataPsw);
                GizManger.getInstance().GizWrite(setPinNum.parse());
                LoadingDailog.Builder loadBuilder=new LoadingDailog.Builder(getContext())
                        .setCancelable(false)
                        .setCancelOutside(false);
                 dialog=loadBuilder.create();
                dialog.show();
                timer.start();
                break;
            case R.id.cb_pin:
                checkBox = cbPin.isChecked();
                PreferencesUtil.getInstance(getContext()).putBoolean("CBPIN",checkBox);
                break;
        }
    }

    @Override
    public void onResume() {

        super.onResume();
    }

    @Override
    public void onStop() {
        if (isAppOnForeground()){
            MyLog.i("是否在前台", "onResume:是 ");
        }else {
            MyLog.i("是否在前台", "onResume:否 ");
            GizManger.getInstance().unSubcriber();
            pop();
        }
        super.onStop();
        MyLog.i("Activity生命周期", "onStop: "+this.toString());
    }

    /**
     * 判断app是否处于前台
     */
    private boolean isAppOnForeground() {

        ActivityManager activityManager = (ActivityManager) Objects.requireNonNull(getContext())
                .getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = getContext().getPackageName();
        /*
         * 获取Android设备中所有正在运行的App
         */
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }
    @Override
    public void onDestroy() {
        if (timer!=null){
            timer.cancel();
        }
        super.onDestroy();
        MyLog.i("Activity生命周期", "onDestroy: "+this.toString());
    }

    @Override
    public boolean onBackPressedSupport() {
        if (System.currentTimeMillis() - TOUCH_TIME >= WAIT_TIME){
            TOUCH_TIME = System.currentTimeMillis();
            GizManger.getInstance().unSubcriber();
        }

        return true;
    }

    @Override
    public void didSetSubscribe(GizWifiErrorCode result, GizWifiDevice device, boolean isSubscribed) {
        if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
            // 订阅或解除订阅成功
            MyLog.i("订阅", "订阅成功：" + this.toString()  );
        } else {
            // 失败
            Intent intent = new Intent(getContext(), DeviceListActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            MyLog.i("订阅", "订阅失败：" + this.toString() );
        }
    }

    @Override
    public void didReceiveData(GizWifiErrorCode result, GizWifiDevice device, ConcurrentHashMap<String, Object> dataMap, int sn) {
        MyLog.i("收到数据",dataMap.toString());
        if (dataMap.get("binary") != null) {
//            ConcurrentHashMap<String, Object> map = (ConcurrentHashMap<String, Object>) dataMap.get("binary");
            // 扩展数据点，key为"kuozhan"
            byte[] bytes = (byte[]) dataMap.get("binary");
            byte[] dataArea;
            FrameType identify = FrameUtils.getDataIdentifyEnum(bytes);
            MyLog.i("1234", "didReceiveData: " + identify);
            if(identify == FrameType.TYPE_FRAME_ROBOT_PIN_QUERY){
                dataArea = FrameUtils.getDataArea(bytes);
                String dataA = HexStrUtils.bytesToHexString(dataArea);
                MyLog.i("1234", "didReceiveData: " + dataA);
                String psw = Objects.requireNonNull(etDevicePassword.getText()).toString();
                if (timer!=null){
                    timer.cancel();
                }
                if (dialog!=null){
                    dialog.dismiss();
                }
                if (dataA.equals("01")){
                    Intent intent = new Intent(getContext(), DeviceMainActivity.class);
                    startActivity(intent);
                    Handler handler = new Handler();
                    handler.postDelayed(() -> {
                        if (checkBox){
                            PreferencesUtil.getInstance(getContext()).putString("PIN",psw);
                        } else {
                            PreferencesUtil.getInstance(getContext()).putString("PIN",null);
                        }
                        pop();
                    }, 500);
                } else {
                    Toast.makeText(getContext(),"wrong password", Toast.LENGTH_SHORT).show();
                }
            }
            String string = HexStrUtils.bytesToHexString(bytes);
            MyLog.i("收到数据","string:"+string);
//            Toast.makeText(getContext(), string, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void didGetHardwareInfo(GizWifiErrorCode result, GizWifiDevice device, ConcurrentHashMap<String, String> hardwareInfo) {

    }

    @Override
    public void didSetCustomInfo(GizWifiErrorCode result, GizWifiDevice device) {

    }

    @Override
    public void didUpdateNetStatus(GizWifiDevice device, GizWifiDeviceNetStatus netStatus) {
        if (this.getContext()!=null){
            if (netStatus != GizWifiDeviceNetStatus.GizDeviceControlled) {
                //GizManger.getInstance().removeCallback();
                //20200804 yuFeng
                if (device.isSubscribed()){
                    GizManger.getInstance().unSubcriber();
                }
                Intent intent = new Intent(getContext(), DeviceListActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        }

    }

    /**
     * 开始进度
     */

    private CountDownTimer timer = new CountDownTimer(10000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
        }

        @Override
        public void onFinish() {
            Toast.makeText(getContext(),"time out ",Toast.LENGTH_SHORT).show();
            if (dialog!=null){
                dialog.dismiss();
            }
        }
    };
}
